﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BuildPlannerLib.Enums;
using BuildPlannerLib.SimEvents;

namespace BuildPlannerLib.PlayerActions
{
    // Derived class of Action for transferring workers to a different base
    public class TransferWorker : PlayerAction
    {
        // Base fields for the bases involved
        public Base StartingBase;
        public Base EndingBase;

        // Constructor with parameters for each base and time
        public TransferWorker(Base startingbase, Base endingbase, int time)
        {
            StartingBase = startingbase;
            EndingBase = endingbase;
            TimeDuration = time;
            Description = "Transfer Worker (Base " + Build.Map.Bases.IndexOf(StartingBase) + " to " + Build.Map.Bases.IndexOf(EndingBase) + ")";
            LongDescription = "Transferring a worker from base number " + Build.Map.Bases.IndexOf(StartingBase) + " to " + Build.Map.Bases.IndexOf(EndingBase) + " over " + TimeConvert.ToTimeSpan(TimeDuration).ToString("g") + ".";
        }

        // Evaluates whether there is at least one worker at the starting base and whether there is an expansion started at the ending base
        public override bool RequirementsFilled()
        {
            Error = null;

            if (StartingBase.MineralWorkers == 0)
            {
                Error = "No workers assigned to minerals at the specified base.";
                return false;
            }

            if (EndingBase.Status == BaseStatus.NotTaken)
            {
                Error = "The base where the transfer is specified to end at has not been taken";
                return false;
            }

            return base.RequirementsFilled();
        }

        // Evaluates if the expansion is finished at the ending base and if there is a worker in the Leaving, Close, or Idle category
        public override bool StartCheck()
        {
            if (EndingBase.Status != BaseStatus.ExpandFinished)
                return false;

            if (StartingBase.MineralWorkerStatus.Sum() == 0)
                return false;

            return base.StartCheck();
        }

        // Removes the worker from the starting base and adds the event for finishing the action
        public override void StartAction()
        {
            base.StartAction();

            StartingBase.RemoveMineralWorker(ref Build);
            Build.Player.IdleWorkers++;
        }

        // Adds the worker to the new base
        public override void FinishAction()
        {
            base.FinishAction();

            Build.Player.IdleWorkers--;
            EndingBase.AddMineralWorker(ref Build);
        }
    }
}
